let { token } = require("./token_schema.js");
let { user } = require("../login/sign_schma.js");
let crypto = require("crypto");
function GJ_randomNum() {
    return Math.floor(Math.random() * 10);
}
//返回一个len位随机数字字符串
function GJ_randomStr(len) {
    let str = ""
    for (let i = 0; i < len; i++) {
        str += GJ_randomNum();
    }
    return str;
}
function encrypt(data) {
    const key = Buffer.from('9vApxLk5G3PAsJrM', 'utf8');
    const iv = Buffer.from('FnJL7EDzjqWjcaY9', 'utf8');
    let sign = '';
    const cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
    sign += cipher.update(data, 'utf8', 'hex');
    sign += cipher.final('hex');
    return sign;
}
module.exports = {
    addToken: async function (tokenData) {
        tokenData.random = GJ_randomNum();
        tokenData.randomStr = GJ_randomStr(8);
        tokenData.token = encrypt(`${tokenData.randomStr}-${tokenData.user}-${tokenData.random}-${tokenData.outTime}`);
        let len = await token.countDocuments({ user: tokenData.user });
        if (len > 0) {
            await token.updateOne({ user: tokenData.user }, { $set: tokenData }).then((data) => {
                // console.log(data, "更新token");
                return Promise.resolve("true");
            })
        } else {
            await token.create(tokenData).then((data) => {
                // console.log(data, "创建token");
                return Promise.resolve("true");
            })
        }

        await user.updateOne({ user: tokenData.user }, { $set: { token: tokenData.token } }).then((userData) => {
            console.log(userData, "用户更新token值");
            return Promise.resolve("true");
        })
        return Promise.resolve("true")
    }
}